//这文件专门处理文章相关路由
const express = require('express')
const router = express.Router()
const fs = require('fs')
const path = require('path')
const multer = require('multer')

// 配置图片文件路径
const upload = multer({
    dest:"./uploads"
})
//引入数据库相关的model文件
const PostModel = require('../models/posts')
const UserModel = require('../models/user')
//  在 router 对象上处理路由的请求
// 新增文章
router.post('/api/posts', async (req, res) => {
    //1.获取前端传递过来的参数 req.body
    // 2.写入数据库中
    const post = new PostModel(req.body)
    try {
        const data = await post.save()
        console.log(data);
        res.send({
            code: 0,
            msg: 'ok'
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: -1,
            msg: '错了'
        })
    }
})
//查询文章
router.get('/api/posts', async (req, res) => {
    // res.writeHead(200, {
    //     'Access-Control-Allow-Origin': '*',
    // })
    //1.取出前端传递过来的参数
    let pageNum = parseInt(req.query.pageNum) || 1
    let pageSize = parseInt(req.query.pageSize) || 5
    let title = req.query.title

    //2.获取文章列表
    const posts = await PostModel.find({ title: new RegExp(title) })
        .skip((pageNum - 1) * pageSize).limit(pageSize)
    //3.获取文章总条数
    const count = await PostModel.find({ title: new RegExp(title) }).countDocuments()
    //4.响应给前端
    res.send({
        code: '0',
        msg: 'ok',
        date: {
            list: posts,
            count
        }
    })
})
// 删除文章
router.delete('/api/posts/:id', async (req, res) => {
    console.log(9999)
    //1.取出需要删除的文章id
    let id = req.params.id
    console.log(id)
    //2.删除
    const data = await PostModel.deleteOne({_id:id})
    console.log(data)
    //3.响应
    res.send({
        code: 0,
        msg: 'ok'
    })
})
//修改文章
router.put('/api/posts/:id/update', async (req, res) => {
    //1.取出需要删除的文章id
    let id = req.params.id
    // 2. 取出要修改的内容
    console.log(req.body, id)
    let title = req.body.title
    await PostModel.updateMany({ _id: id }, req.body)
    // 3.响应
    res.send({
        code: 0,
        msg: 'ok'
    })
})
//----------------------------------------------

//文章列表页面
router.get('/', async (req, res) => {
    //当前用户的登录姓名
    let username = req.userInfo.username
    let pageNum = parseInt(req.query.pageNum) || 1
    let pageSize = parseInt(req.query.pageSize) || 5

    const _user = await UserModel.findOne({username})
    let headc = _user.headc
    //1.获取数据
    const _posts = await PostModel.find().skip((pageNum - 1) * pageSize)
        .limit(pageSize).sort({ _id: -1 })
    let posts = []

    _posts.forEach(async post =>{
        let obj = JSON.parse(JSON.stringify(post))
        // 1.取出没篇文章的用户id
        let userId = post.user;
        // console.log(post)
        //2.根据这个用户id去获取相应的用户信息
        let user = await UserModel.findById(userId)
        obj.user = user
        posts.push(obj)
    })
    //获取总条数
    const count = await PostModel.find().countDocuments()
    //算出页数
    const totalPages = Math.ceil(count / pageSize)

    const orig = req.originalUrl
    res.render('post/index', { posts, totalPages, pageNum,orig,username,headc})
})
//更换头像处理
router.post('/postss',upload.single('headc'), async (req, res)=>{
    let username = req.userInfo.username

    const fileData = fs.readFileSync(
        path.resolve(__dirname,"../uploads",req.file.filename)
    );

    //2.构建一个路径，piblic目录下的路径
    const filename = new Date().getTime() + '-' + req.file.originalname
    const filePath = path.resolve(__dirname,'../piblic/',filename)
    //3.写文件
    fs.writeFileSync(filePath,fileData)
    let headc = `http://localhost:8080/${filename}`
    await UserModel.updateOne({username:username},{headc:headc})
    res.redirect('/posts')
 
    // 获取分页的参数
})
// 文章新增页面
router.get('/create',async (req, res) => {
    res.render('post/create')
})
//文章新增处理
router.post('/store',upload.single('picture'),async (req, res) => {
      //想办法吧upload里的临时文件放置到piblic（静态文件）目录下
    //1.使用fs.feadFileSyne()读取文件内容

    const fileData = fs.readFileSync(
        path.resolve(__dirname,"../uploads",req.file.filename)
    );

    //2.构建一个路径，piblic目录下的路径
    const filename = new Date().getTime() + '-' + req.file.originalname
    const filePath = path.resolve(__dirname,'../piblic/',filename)
    //3.写文件
    fs.writeFileSync(filePath,fileData)
    
    //4.将传的文件路径给设置到当前文章的picture属性上
    let body ={
        ...req.body,
        user:req.userInfo.userId,
        picture:`http://localhost:8080/${filename}`
    }
    const post = new PostModel(body)
    await post.save()
    //回到文章列表页
    res.redirect('/posts')
})
//文章详情页面
router.get('/:id',async (req, res) => {
    let id = req.params.id
    const post = await PostModel.findOne({ _id: id })
    res.render('post/show', { post })
})
//end 将这个router对象暴露出去
module.exports = router
